package com.example.wowangz.rabbitmq;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {

	/** 消息交换机的名字 */
	public static final String EXCHANGE = "my-mq-exchange";
	/** 队列key1 */
	public static final String ROUTINGKEY1 = "queue_one_key";
	/** 队列key2 */
	public static final String ROUTINGKEY2 = "queue_two_key";

	@Value("${rabbitmq.host}")
	private String host;

	@Value("${rabbitmq.port}")
	private int port;

	@Value("${rabbitmq.username}")
	private String username;

	@Value("${rabbitmq.password}")
	private String password;

	/**
	 * 根据配置属性连接RabbitMQ
	 * 
	 * @return
	 */
	@Bean
	public ConnectionFactory connectionFactory() {
		CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host, port);
		connectionFactory.setUsername(username);
		connectionFactory.setPassword(password);
		connectionFactory.setVirtualHost("/");
		connectionFactory.setPublisherConfirms(true); // 必须要设置

		return connectionFactory;
	}

	/**
	 * 配置消息交换机 针对消费者配置 FanoutExchange: 将消息分发到所有的绑定队列，无routingkey的概念
	 * HeadersExchange ：通过添加属性key-value匹配 DirectExchange:按照routingkey分发到指定队列
	 * TopicExchange:多关键字匹配
	 */
	@Bean
	public DirectExchange defaultExchange() {
		return new DirectExchange(EXCHANGE, true, false);
	}

	/**
	 * 配置消息队列1
	 * 
	 * @return
	 */
	@Bean({ "queue_one" })
	public Queue queueOne() {
		return new Queue("queue_one", true); // 队列持久
	}

	/**
	 * 配置消息队列2
	 * 
	 * @return
	 */
	@Bean({ "queue_two" })
	public Queue queueTwo() {
		return new Queue("queue_two", true); // 队列持久
	}

	/**
	 * 将消息队列1与交换机绑定 针对消费者配置
	 * 
	 * @return
	 */
	@Bean
	public Binding bindingQueueOne() {
		return BindingBuilder.bind(queueOne()).to(defaultExchange()).with(RabbitMQConfig.ROUTINGKEY1);
	}

	/**
	 * 将消息队列2与交换机绑定 针对消费者配置
	 * 
	 * @return
	 */
	@Bean
	public Binding bindingQueueTwo() {
		return BindingBuilder.bind(queueTwo()).to(defaultExchange()).with(RabbitMQConfig.ROUTINGKEY2);
	}

}
